
package com.gcloud.mesh.dcs.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;

import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import com.gcloud.mesh.dcs.entity.ModelFactorEntity;
import com.gcloud.mesh.header.enums.ModelType;
import com.gcloud.mesh.header.vo.dcs.ModelFactorVo;

@Repository
public class ModelFactorDao extends JdbcBaseDaoImpl<ModelFactorEntity, String> {

	public <E> List<E> getByModelType(ModelType t, Class<E> clazz) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(" SELECT *,(score_sample-score_history) as diff FROM dcs_model_factors where model_type = ? ");
		buffer.append(" order by id asc ");
		List<Object> values = new ArrayList<>();
		values.add(t.name());
		return this.findBySql(buffer.toString(), values, clazz);
		// return this.findByProperty("modelType", t.name(), "id", "ASC", clazz);
	}

	public void updateBatchBest(ModelFactorVo[] factors) {
		String sql = "UPDATE dcs_model_factors SET score_best_predict = ?  WHERE id = ?";
		this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setInt(1, factors[i].getScoreBestPredict());
				ps.setString(2, factors[i].getId());
			}

			@Override
			public int getBatchSize() {
				return factors.length;
			}
		});
    }

	public void updateBatch(ModelFactorVo[] factors) {
		//String sql = "UPDATE dcs_model_factors SET enabled = ?, score_sample = ?, score_type = ?, weight = ? WHERE id = ?";
		String sql = "UPDATE dcs_model_factors SET enabled = ?, score_sample = ? WHERE id = ?";
		this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setBoolean(1, factors[i].getEnabled());
				ps.setInt(2, factors[i].getScoreSample());
				//ps.setString(3, factors[i].getScoreType());
				//ps.setInt(4, factors[i].getWeight());
				ps.setString(3, factors[i].getId());
			}

			@Override
			public int getBatchSize() {
				return factors.length;
			}
		});
	}
	public void updateHistoryAndSample(String type) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("update dcs_model_factors a , (select score_sample, score_best_predict , id from dcs_model_factors ) b set a.score_history = b.score_sample, a.score_sample = b.score_best_predict where a.id = b.id ");
		buffer.append(" and model_type = ? ");
		this.jdbcTemplate.update(buffer.toString(), type);
	}

}
